/**
 * 
 */
package com.nari.basic.action;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.struts2.json.JSONUtil;
import org.apache.struts2.json.annotations.JSON;

import com.nari.basic.model.IMenu;
import com.nari.basic.model.IRole;
import com.nari.basic.model.IUser;
import com.nari.basic.service.IMenuService;
import com.nari.basic.service.IRoleService;
import com.nari.basic.service.IUserService;
import com.nari.basic.utils.sysmgr.UserRoleUtil;
import com.nari.coreframe.action.struts2.JSONActionSupport;
import com.nari.coreframe.webframe.SysEnvironmentMgr;
import com.nari.platform.model.ResponseMsg;
import com.nari.platform.model.WebConstants;
import com.nari.platform.security.MD5Encoder;
import com.opensymphony.xwork2.Action;

/**
 * 
 * @author Xiaopeng
 * @date 2013-7-22
 */
public class LoginAction extends JSONActionSupport {
	private static final long serialVersionUID = -8584768706047536357L;
	private String sysSecurity;
	private IUserService iUserService;
	private IMenuService iMenuService;
	private IRoleService iRoleService;
	//用户登录
	private String userID;
	private String password;	
	//用户修改密码
	private String rePassword; 
	//用户菜单
	private List<IMenu> authorityMenuList;
	private List<IMenu> rootMenuList;
	
	/**
	 * 用户登录
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-22
	 */
	public String login() throws Exception {
		this.password = MD5Encoder.getMD5String(password);
		String loginStr = this.userID + "=" + this.password;
		System.out.println(">>LoginInfo:"+loginStr);
		HttpSession session = SysEnvironmentMgr.getSessionInstance();
		if(this.sysSecurity.indexOf(loginStr)>-1){	//系统管理员登录
			//创建系统管理员用户
			IUser superManager = new IUser();
			superManager.setUserID(userID);
			superManager.setUserName(userID);
			superManager.setPassword(password);
			//向session中加入管理员用户信息
			session.setAttribute(WebConstants.USER_SESSION, superManager);
			//读取管理员权限菜单信息
			List<IMenu> menuList = this.iMenuService.queryAllMenusInOrder();
			session.setAttribute(WebConstants.USER_MENUS, menuList);
			return "loginSuccess";
		} else { //用户登录
			IUser loginUser = this.iUserService.queryLoginUser(userID, password);
			if(loginUser != null) {
				//验证用户信息是否有效可用："1"表示有效，"0"或其他表示无效
				if(!"1".equals(loginUser.getStatus())) {
					session.setAttribute(WebConstants.LOGIN_FAIL_TIPS, "Please contact administrator！");
					return Action.INPUT;
				}
				//向session中加入用户登录信息
				session.setAttribute(WebConstants.USER_SESSION, loginUser);
				//读取用户的角色信息
				List<IRole> roleList = this.iRoleService.queryRolesByUserUID(loginUser.getId());
				String roleIDs = UserRoleUtil.formatRoleIDByRoleList(roleList);
				session.setAttribute(WebConstants.USER_ROLES, roleList);
				session.setAttribute(WebConstants.USER_ROLEIDS, roleIDs);
				//读取用户的权限菜单信息
				String roleUIDs = UserRoleUtil.formatIDByRoleList(roleList);
				List<IMenu> menuList = this.iMenuService.queryUserMenuByRoleUIDs(roleUIDs);
				session.setAttribute(WebConstants.USER_MENUS, menuList);
				return "loginSuccess";
			} else { //用户登录失败
				session.setAttribute(WebConstants.LOGIN_FAIL_TIPS, "User name or password incorrect!");
				return Action.INPUT;
			}
		}
	}
	
	/**
	 * 用户注销登录 
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-22
	 */
	public String logout() throws Exception {
		HttpSession session = SysEnvironmentMgr.getSessionInstance();
		session.invalidate();
		return Action.INPUT;
	}
	
	/**
	 * 用户修改密码
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-22
	 */
	public String modifyPwd() throws Exception {
		//校验原密码是否输入正确
		this.password = MD5Encoder.getMD5String(password);
		HttpSession session = SysEnvironmentMgr.getSessionInstance();
		IUser loginUser = (IUser) session.getAttribute(WebConstants.USER_SESSION);
		//系统管理员密码不可以修改
		String loginStr = loginUser.getUserID() + "=" + loginUser.getPassword();
		if(this.sysSecurity.indexOf(loginStr)>-1){
			this.rmsg = ResponseMsg.getInstance(false, loginUser.getUserID()+"password can't be modified!");
			this.writeJsonStrToResponse(JSONUtil.serialize(this.rmsg));
			return Action.SUCCESS;
		}
		//原密码输入错误
		if(!loginUser.getPassword().equals(password)) {
			this.rmsg = ResponseMsg.getInstance(false, "password  incorrect!");
			this.writeJsonStrToResponse(JSONUtil.serialize(rmsg));
			return Action.SUCCESS;
		}
		//更新密码
		this.rePassword = MD5Encoder.getMD5String(rePassword);
		if(!loginUser.getPassword().equals(rePassword)) {
			loginUser.setPassword(rePassword);
			this.iUserService.updateEntity(loginUser, loginUser.getId());
			session.setAttribute(WebConstants.USER_SESSION, loginUser);
		}
		this.writeJsonStrToResponse(JSONUtil.serialize(ResponseMsg.getInstance(true, "password modified successfully!")));
		return Action.SUCCESS; 
	}
	
	/**
	 * 根据登录用户角色权限控制加载的页面
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-7-23
	 */
	@SuppressWarnings("unchecked")
	public String initialUserAuthority() throws Exception {
		HttpSession session = SysEnvironmentMgr.getSessionInstance();
		IUser loginUser = (IUser) session.getAttribute(WebConstants.USER_SESSION);
		String loginStr = loginUser.getUserID() + "=" + loginUser.getPassword();
		//判断是管理员登录，还是普通用户登录，并分别转发不同页面
		if(this.sysSecurity.indexOf(loginStr)>-1){
			return "systemMgr"; //系统管理
		} else {
			//用户权限菜单
			this.authorityMenuList = (List<IMenu>) session.getAttribute(WebConstants.USER_MENUS);
			//用户一级菜单
			this.rootMenuList = this.iMenuService.queryChildMenuByParent(null, authorityMenuList);
			return "functionApp"; //功能应用
		}
	}
	
	/**
	 * @return the sysSecurity
	 */
	public String getSysSecurity() {
		return sysSecurity;
	}

	/**
	 * @param sysSecurity the sysSecurity to set
	 */
	public void setSysSecurity(String sysSecurity) {
		this.sysSecurity = sysSecurity;
	}

	/**
	 * @return the iUserService
	 */
	@JSON(serialize=false)
	public IUserService getiUserService() {
		return iUserService;
	}
	
	/**
	 * @param iUserService the iUserService to set
	 */
	public void setiUserService(IUserService iUserService) {
		this.iUserService = iUserService;
	}
	
	/**
	 * @return the iMenuService
	 */
	@JSON(serialize=false)
	public IMenuService getiMenuService() {
		return iMenuService;
	}
	
	/**
	 * @param iMenuService the iMenuService to set
	 */
	public void setiMenuService(IMenuService iMenuService) {
		this.iMenuService = iMenuService;
	}
	
	/**
	 * @return the iRoleService
	 */
	@JSON(serialize=false)
	public IRoleService getiRoleService() {
		return iRoleService;
	}
	
	/**
	 * @param iRoleService the iRoleService to set
	 */
	public void setiRoleService(IRoleService iRoleService) {
		this.iRoleService = iRoleService;
	}

	/**
	 * @return the userID
	 */
	public String getUserID() {
		return userID;
	}

	/**
	 * @param userID the userID to set
	 */
	public void setUserID(String userID) {
		this.userID = userID;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the rePassword
	 */
	public String getRePassword() {
		return rePassword;
	}

	/**
	 * @param rePassword the rePassword to set
	 */
	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}

	/**
	 * @return the authorityMenuList
	 */
	public List<IMenu> getAuthorityMenuList() {
		return authorityMenuList;
	}

	/**
	 * @param authorityMenuList the authorityMenuList to set
	 */
	public void setAuthorityMenuList(List<IMenu> authorityMenuList) {
		this.authorityMenuList = authorityMenuList;
	}

	/**
	 * @return the rootMenuList
	 */
	public List<IMenu> getRootMenuList() {
		return rootMenuList;
	}

	/**
	 * @param rootMenuList the rootMenuList to set
	 */
	public void setRootMenuList(List<IMenu> rootMenuList) {
		this.rootMenuList = rootMenuList;
	}

}
